package cn.cocho.android.mc.file;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import cn.cocho.android.mc.log.LoggerUtils;
import cn.cocho.android.mc.util.CommonContexts;

/**
 * 文件下载
 * 
 * @author HAIKANG SONG
 * @time 2013-4-24上午10:31:28
 */
public class FileDownload {

	/**
	 * 下载文件并保存到本地
	 * 
	 * @param url
	 *            文件在网络上的路径
	 * @param savePath
	 *            本地保存路径
	 * @return
	 * @author HAIKANG SONG
	 * @time 2013-4-24上午10:46:44
	 */
	public static boolean download(String url, String savePath) {
		boolean result = false;
		File file = FileUtils.getFile(savePath);
		InputStream in = null;
		FileOutputStream fout = null;
		try {
			URL u = new URL(url);// 获得被下载文件的路径
			in = u.openStream();// 打开到此 URL的连接并返回一个用于从该连接读入的 InputStream。
			fout = new FileOutputStream(file);// 生成文件输出流
			byte[] buffer = new byte[CommonContexts.fileBuffer];// 写文件时的缓冲区
			int byteRead = 0;
			while ((byteRead = in.read(buffer)) > 0) {
				fout.write(buffer, 0, byteRead);
			}
			result = true;
		} catch (Exception e) {
			LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件并保存到(" + savePath + ")时出错", e);
			FileUtils.delete(file);
		} finally {
			try {
				if (in != null) {
					in.close();
				}
				if (fout != null) {
					fout.flush();
					fout.close();
				}
			} catch (Exception e) {
				FileUtils.delete(file);
			}
		}
		return result;
	}

	/**
	 * 从网络上下载一个文件前面指定字节数的部分
	 * 
	 * @param url
	 *            文件在网络上的路径
	 * @param byteSize
	 *            下载多少个字节
	 * @return
	 * @author HAIKANG SONG
	 * @time 2013-4-24上午10:53:51
	 */
	public static byte[] downLoad(String url, int byteSize) {
		byte[] result = new byte[byteSize];
		InputStream in = null;
		try {
			URL u = new URL(url);
			HttpURLConnection connection = (HttpURLConnection) u.openConnection();
			in = connection.getInputStream();
			in.read(result);
		} catch (MalformedURLException e) {
			LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);
		} catch (IOException e) {
			LoggerUtils.error(FileDownload.class.getName(), "从(" + url + ")下载文件的前" + byteSize + "个字节时出错", e);
		} finally {
			try {
				in.close();
			} catch (Exception e) {
			}
		}
		return result;
	}

	public static long getUrlFileLength(String url) {
		long length = 0;
		// HttpClient client = new DefaultHttpClient();
		// HttpGet httpGet = new HttpGet();
		// httpGet.setURI(new URI(url));
		// HttpResponse response = client.execute(httpGet);
		// HttpEntity entity = response.getEntity();
		// length = entity.getContentLength();
		// client.getConnectionManager().shutdown();
		return length;
	}

}
